package io.renren.modules.companys.controller;

import java.util.*;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.CommonBusinessStatus;
import io.renren.modules.common.dao.CompanyWelfareDao;
import io.renren.modules.common.dao.PositionCertificateDao;
import io.renren.modules.common.dao.PositionWelfareDao;
import io.renren.modules.common.entity.CompanyWelfareEntity;
import io.renren.modules.common.entity.PositionCertificateEntity;
import io.renren.modules.common.entity.PositionWelfareEntity;
import io.renren.modules.common.service.CompanyWelfareService;
import io.renren.modules.common.service.PositionCertificateService;
import io.renren.modules.common.service.PositionWelfareService;
import io.renren.modules.common.viewdo.SelectOption;
import io.renren.modules.common.viewdo.TreeOption;
import io.renren.modules.companys.dao.CompanyDao;
import io.renren.modules.companys.entity.dto.CompanyEntityDTO;
import io.renren.modules.workjobs.dao.WorkJobDao;
import io.renren.modules.workjobs.entity.WorkJobEntity;
import io.renren.modules.workjobs.service.WorkJobService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.companys.entity.CompanyEntity;
import io.renren.modules.companys.service.CompanyService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;



/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2022-03-07 17:24:36
 */
@RestController
@RequestMapping("companys/company")
public class CompanyController {
    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyWelfareService companyWelfareService;

    @Autowired
    private CompanyWelfareDao companyWelfareDao;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private WorkJobDao workJobDao;

    @Autowired
    private WorkJobService workJobService;

    @Autowired
    private PositionCertificateDao positionCertificateDao;
    @Autowired
    private PositionWelfareService positionWelfareService;

    @Autowired
    private PositionWelfareDao positionWelfareDao;
    @Autowired
    private PositionCertificateService positionCertificateService;



    @GetMapping("/tree-option-pcr")
    public R treeOptionPCR(){
        List<TreeOption> treeOptionList = companyService.treeOPtionPCR();
        return R.ok().put("data",treeOptionList);
    }
    @GetMapping("/tree-option-prc/{userId}")
    public R treeOptionPRCUser(@PathVariable("userId")String userId){
        QueryWrapper<CompanyEntity> wapper = new QueryWrapper<>();
        wapper.eq("create_user_id",userId);
        CompanyEntity company = companyService.getOne(wapper);
        List<String> listData = new ArrayList<>();
        listData.add(company.getProvincesId());
        listData.add(company.getCityesId());
        listData.add(company.getAreasId());
        return R.ok().put("data",listData);
    }

    @GetMapping("/option-welfare/{userId}")
    public R selectOptionWelfare(@PathVariable("userId")String userId){
        //根据用户查询出来企业的信息
        QueryWrapper<CompanyEntity> wapper = new QueryWrapper<>();
        wapper.eq("create_user_id",userId);
        CompanyEntity company = companyService.getOne(wapper);

        QueryWrapper<CompanyWelfareEntity> companyWelfareEntityQueryWrapper = new QueryWrapper<>();
        companyWelfareEntityQueryWrapper.eq("company_id",company.getId());

        List<CompanyWelfareEntity> companyWelfareEntities = companyWelfareDao.selectList(companyWelfareEntityQueryWrapper);
        List<String> listDate = companyWelfareEntities.stream().map(item -> item.getWelfareId().toString()).collect(Collectors.toList());
        return R.ok().put("data",listDate);
    }

    @GetMapping("/select-option")
    public R selectOption(){
        List<SelectOption> listData = companyService.selectOption();
        return R.ok().put("data",listData);
    }


    @GetMapping("/tree-option-need-info/{companyId}")
    public R selectTreeOptionPCRByCompanyId(@PathVariable("companyId")String companyId){
        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",companyId);
        CompanyEntity companyEntity = companyDao.selectOne(wrapper);

        List<String> listDataIndustory = new ArrayList<>();
        List<String> listDataAddress = new ArrayList<>();


        List<String> listDataWelfare = new ArrayList<>();

        if(companyEntity!=null){
            listDataAddress.add(companyEntity.getProvincesId());
            listDataAddress.add(companyEntity.getCityesId());
            listDataAddress.add(companyEntity.getAreasId());

            listDataIndustory.add(companyEntity.getTradeId().toString());
            listDataIndustory.add(companyEntity.getClassifyId().toString());
            listDataIndustory.add(companyEntity.getJobTypeId().toString());

            QueryWrapper<CompanyWelfareEntity> welfareEntityQueryWrapper = new QueryWrapper<>();
            welfareEntityQueryWrapper.eq("company_id",companyId);

            List<CompanyWelfareEntity> companyWelfareEntities = companyWelfareDao.selectList(welfareEntityQueryWrapper);
            listDataWelfare = companyWelfareEntities.stream().map(item -> item.getWelfareId().toString()).collect(Collectors.toList());
        }


        return R.ok().put("listDataAddress",listDataAddress)
                     .put("listDataIndustory",listDataIndustory)
                     .put("listDataWelfare",listDataWelfare);
    }


    @PostMapping("/updateCompanyStatus/{companyId}")
    public R updateCompanyStatus(@PathVariable("companyId")String companyId){


        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",companyId);
        CompanyEntity companyEntity = companyDao.selectOne(wrapper);
        if(!(CommonBusinessStatus.COMPANY_HAVE_APPROVE.equals(companyEntity.getCompanyApproveStatus()))){
            companyEntity.setCompanyApproveStatus(CommonBusinessStatus.COMPANY_HAVEING_APPROVE);
            companyDao.updateById(companyEntity);
        }
        return R.ok();
    }






    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("companys:company:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = companyService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 客户端信息
     */
    @GetMapping("/info-client/{id}")
    @RequiresPermissions("companys:company:info")
    public R infoCilent(@PathVariable("id") String userId){
        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper();
        wrapper.eq("create_user_id",userId);
        CompanyEntity company =companyService.getOne(wrapper);
        return R.ok().put("company", company);
    }
    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("companys:company:info")
    public R info(@PathVariable("id") String id){
		CompanyEntity company = companyService.getById(id);

        return R.ok().put("company", company);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @Transactional
    @RequiresPermissions("companys:company:save")
    public R save(@RequestBody CompanyEntityDTO companyDTO){

        CompanyEntity company = new CompanyEntity();
        BeanUtils.copyProperties(companyDTO,company);
        company.setIsPass(0);
        company.setCompanyApproveStatus(CommonBusinessStatus.COMPANY_NOT_APPROVE);
        companyService.save(company);

        ArrayList<String> companyWalfare = companyDTO.getCompanyWalfare();
        if (companyWalfare != null){
            List<CompanyWelfareEntity> welfareEntityList = companyWalfare.stream().map(item -> new CompanyWelfareEntity(Integer.parseInt(item), company.getId())).collect(Collectors.toList());
            companyWelfareService.saveBatch(welfareEntityList);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    @RequiresPermissions("companys:company:update")
    public R update(@RequestBody CompanyEntityDTO companyEntityDTO){
        CompanyEntity company = new CompanyEntity();
        BeanUtils.copyProperties(companyEntityDTO,company);
		companyService.updateById(company);
        ArrayList<String> companyWalfare = companyEntityDTO.getCompanyWalfare();
        QueryWrapper<CompanyWelfareEntity> wrapper = new QueryWrapper<>();
        if (companyWalfare!=null){
            List<CompanyWelfareEntity> welfareEntityList = companyWalfare.stream().map(item -> new CompanyWelfareEntity(Integer.parseInt(item), company.getId())).collect(Collectors.toList());
            for (CompanyWelfareEntity companyEntity : welfareEntityList){
                wrapper.eq("welfare_id",companyEntity.getWelfareId());
                wrapper.eq("company_id",companyEntity.getCompanyId());
                CompanyWelfareEntity companyWelfareEntity = companyWelfareDao.selectOne(wrapper);
                if (companyWelfareEntity == null){
                    companyWelfareService.save(companyEntity);
                }else{
                    companyWelfareService.updateById(companyWelfareEntity);
                }

            }
           // companyWelfareService.updateBatchById(welfareEntityList);
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("companys:company:delete")
    public R delete(@RequestBody String[] ids){
        List<String> idstr = (List<String>) Arrays.asList(ids);

        //删除企业福利信息
        QueryWrapper<CompanyWelfareEntity> companyWelfareWrapper = new QueryWrapper<>();
        companyWelfareWrapper.in("company_id",idstr);
        List<CompanyWelfareEntity> companyWelfareEntities = companyWelfareDao.selectList(companyWelfareWrapper);
        List<Integer> companyWelfareIds = companyWelfareEntities.stream().map(item -> item.getId()).collect(Collectors.toList());



        QueryWrapper<CompanyEntity> companyEntityWrapper = new QueryWrapper<>();
        companyEntityWrapper.in("id",idstr);
        List<CompanyEntity> companyEntities = companyDao.selectList(companyEntityWrapper);
        List<Long> createUserIds = companyEntities.stream().map(item -> item.getCreateUserId()).collect(Collectors.toList());

        //删除职位信息
        QueryWrapper<WorkJobEntity> workJobWrapper = new QueryWrapper<>();
        workJobWrapper.in("create_user_id",createUserIds);
        List<WorkJobEntity> workJobEntities = workJobDao.selectList(workJobWrapper);
        List<String> workJobIds = workJobEntities.stream().map(item -> item.getId()).collect(Collectors.toList());

        //删除职位福利
        QueryWrapper<PositionWelfareEntity> positionWelfareWrapper = new QueryWrapper<>();
        positionWelfareWrapper.in("position_id",workJobIds);
        List<PositionWelfareEntity> positionWelfareEntities = positionWelfareDao.selectList(positionWelfareWrapper);
        List<Integer> positionWelfareIds = positionWelfareEntities.stream().map(item -> item.getId()).collect(Collectors.toList());

        //删除职位证书
        QueryWrapper<PositionCertificateEntity> positionCertificateWrapper = new QueryWrapper<>();
        positionCertificateWrapper.in("position_id",workJobIds);
        List<PositionCertificateEntity> positionCertificateEntityList = positionCertificateDao.selectList(positionCertificateWrapper);
        List<Integer> positionCertificateIds = positionCertificateEntityList.stream().map(item -> item.getId()).collect(Collectors.toList());


        companyWelfareService.removeByIds(companyWelfareIds);
        positionCertificateService.removeByIds(positionCertificateIds);
        positionWelfareService.removeByIds(positionWelfareIds);
        workJobService.removeByIds(workJobIds);
        companyService.removeByIds(companyWelfareIds);

        return R.ok();
    }


    @RequiresPermissions("companys:company:approve")
    @PostMapping("/approve/{cpmoanyId}/{ispass}")
    public R approveCompany(@PathVariable("cpmoanyId")String companyId,
                            @PathVariable("ispass")String ispass){

        QueryWrapper<CompanyEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id",companyId);
        CompanyEntity entity = companyDao.selectOne(wrapper);

        //如果是说未审核的状态 ， 想要直接通过审核 ，必须要先查看才可以通过
        if (CommonBusinessStatus.COMPANY_NOT_APPROVE.equals(entity.getCompanyApproveStatus())){
            throw new RRException("请先查看并核对企业的信息");
        }

        entity.setCompanyApproveStatus(CommonBusinessStatus.COMPANY_HAVE_APPROVE);
        entity.setIsPass(Integer.parseInt(ispass));
        int isSuccess = companyDao.updateById(entity);
        if (isSuccess>0){
            return R.ok().put("data",true);
        }
        return R.error().put("data",false);
    }
}
